/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/inverted-index-map-reduce
   @Language: C++
   @Datetime: 19-04-05 14:50
   */

/**
 * Definition of Input:
 * template<class T>
 * class Input {
 * public:
 *     bool done(); 
 *         // Returns true if the iteration has elements or false.
 *     void next();
 *         // Move to the next element in the iteration
 *         // Runtime error if the iteration has no more elements
 *     T value();
 *        // Get the current element, Runtime error if
 *        // the iteration has no more elements
 * }
 * Definition of Document:
 * class Document {
 * public:
 *     int id; // document id
 *     string content; // document content
 * }
 */
class InvertedIndexMapper: public Mapper {
public:
	void Map(Input<Document>* input) {
		// Write your code here
		// Please directly use func 'output' to output 
		// the results into output buffer.
		// void output(string &key, int value);
		for(string key; !input->done(); input->next())
			for(stringstream istr(input->value().content); istr>>key;)
				output(key,input->value().id);
	}
};


class InvertedIndexReducer: public Reducer {
public:
	void Reduce(string &key, Input<int>* input) {
		// Write your code here
		// Please directly use func 'output' to output 
		// the results into output buffer.
		// void output(string &key, vector<int> &value);
		// Tip: duplicate id, input has sorted already
		vector<int> v;
		for(; !input->done(); input->next())
			if(v.size()==0 || v.back()!=input->value())
				v.push_back(input->value());
		output(key,v);
	}
};
